//
//  NavTabBarController.m
//  NavBar
//
//  Created by zhangyi on 15/12/15.
//  Copyright © 2015年 zhangyi. All rights reserved.
//

#import "NavTabBarController.h"
#define kNavTabBarHeight 40.0f
#define kTabBarAddScale 0.3
#define kTabBarBtnScale 1.0 + kTabBarAddScale
#define kScreen [UIScreen mainScreen]
#define kScreenWidth kScreen.bounds.size.width
#define kScreenHeight kScreen.bounds.size.height

@interface NavTabBarController ()<UIScrollViewDelegate>{
    NSInteger _currentIndex;
    UIScrollView *_mainView;
    UIScrollView *_tabBarScrollView;
    NSArray *_tabBarButtons;
}

@end

@implementation NavTabBarController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self viewInit];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark view init
- (void)viewInit{
    _tabBarScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kNavTabBarHeight)];
    _tabBarScrollView.showsVerticalScrollIndicator = NO;
    _tabBarScrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_tabBarScrollView];
    
    
    _mainView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, kNavTabBarHeight, kScreenWidth, kScreenHeight - kNavTabBarHeight)];
    _mainView.showsHorizontalScrollIndicator = NO;
    _mainView.showsVerticalScrollIndicator = YES;
    _mainView.contentSize = CGSizeMake(_mainView.frame.size.width*self.subControllers.count, _mainView.frame.size.height);
    _mainView.pagingEnabled = YES;
    _mainView.delegate = self;
    
    [self.view addSubview:_mainView];
    

    UIFont *font = [UIFont systemFontOfSize:[UIFont systemFontSize]];
    __block CGFloat tabBarScrollViewContentWidth = 0.0f;
    __block NSMutableArray *buttonArray = [[NSMutableArray alloc] initWithCapacity:self.subControllers.count];
    
    [self.subControllers enumerateObjectsUsingBlock:^(UIViewController *controller, NSUInteger idx, BOOL * _Nonnull stop) {
        [_mainView addSubview:controller.view];
        controller.view.frame = CGRectMake(idx*_mainView.frame.size.width, 0, _mainView.frame.size.width, _mainView.frame.size.height);
        CGSize size = [controller.title sizeWithAttributes:@{NSFontAttributeName:font}];
        
        //init button
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:controller.title forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        button.titleLabel.font = font;
        if(idx == 0){
            button.selected = YES;
            [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            button.transform = CGAffineTransformMakeScale(kTabBarBtnScale,kTabBarBtnScale);
        }
        

        button.frame = CGRectMake(tabBarScrollViewContentWidth, 0, size.width + 40.0f, kNavTabBarHeight);
        button.tag = 100+idx;
        [button addTarget:self action:@selector(tabBarClick:) forControlEvents:UIControlEventTouchUpInside];
        tabBarScrollViewContentWidth += button.frame.size.width;
        
        [_tabBarScrollView addSubview:button];
        [buttonArray addObject:button];
    }];
    _tabBarScrollView.contentSize = CGSizeMake(tabBarScrollViewContentWidth, _tabBarScrollView.frame.size.height);
    _tabBarButtons = [buttonArray copy];
}

- (void)tabBarClick:(UIButton*)button{
    [self buttonStateChange:button];
}

- (void)buttonStateChange:(UIButton*)button{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];

    for (UIButton *btn in _tabBarButtons) {
        if ( btn!=button && btn.selected==YES) {
            btn.selected = NO;
            btn.transform = CGAffineTransformIdentity;
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
    }
    button.selected = YES;
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    button.transform = CGAffineTransformMakeScale(kTabBarBtnScale,kTabBarBtnScale);
    [UIView commitAnimations];
    
    NSInteger index = button.tag-100;
    UIViewController *controller = self.subControllers[index];
    if (controller!=nil) {
        _mainView.contentOffset = CGPointMake(controller.view.frame.origin.x, 0);
    }
    
    //如果button在侧边,则尝试将它挪动中间
    CGFloat wantOffsetX = button.center.x - _tabBarScrollView.frame.size.width/2;
    if (wantOffsetX<0) {
        wantOffsetX = 0;
    }else if(wantOffsetX+_tabBarScrollView.frame.size.width>_tabBarScrollView.contentSize.width){
        wantOffsetX = _tabBarScrollView.contentSize.width - _tabBarScrollView.frame.size.width;
    }

    [UIView animateWithDuration:0.3 animations:^{
        _tabBarScrollView.contentOffset = CGPointMake(wantOffsetX, 0);
    }];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //找到当前在显示的两个viewcontroller,根据x显示的比例,来设置他们的缩放比例,与button的颜色渐变
    CGFloat start = scrollView.contentOffset.x;
    CGFloat end = start + scrollView.frame.size.width;
    NSMutableArray *arr = [@[] mutableCopy];

    //subcontroller显示方式为从左到右
    for (UIViewController *controller in self.subControllers) {
        CGFloat x =controller.view.frame.origin.x;
        CGFloat xEnd = x + controller.view.frame.size.width;
        if (x==start && xEnd == end) {
            arr = [@[controller] mutableCopy];
            break;
        }
        if ((x<=start && xEnd>=start)
            || (x<=end && xEnd>=end)) {
            [arr addObject:controller];
        }
    }
    
    assert(arr.count>0 && arr.count <=2);
    if (arr.count==2) {
        UIViewController *controllerLeft = [arr firstObject];
        UIViewController *controllerRight = [arr lastObject];
        UIButton *button1 = [_tabBarButtons objectAtIndex:[self.subControllers indexOfObject:controllerLeft]];
        UIButton *button2 = [_tabBarButtons objectAtIndex:[self.subControllers indexOfObject:controllerRight]];
        //计算 controller1 与controller2 在屏幕上显示的比例
        CGFloat controllerLeftWidthInScreen = controllerLeft.view.frame.origin.x + controllerLeft.view.frame.size.width - start;
        CGFloat controllerRightWidthInScreen = end - controllerRight.view.frame.origin.x;
        
        CGFloat controllerLeftPercentage = controllerLeftWidthInScreen/_mainView.frame.size.width;
        CGFloat controllerRightPercentage = controllerRightWidthInScreen/_mainView.frame.size.width;
        
        button1.transform = CGAffineTransformMakeScale(kTabBarAddScale*controllerLeftPercentage + 1, kTabBarAddScale*controllerLeftPercentage + 1);
        
        button2.transform = CGAffineTransformMakeScale(kTabBarAddScale*controllerRightPercentage + 1, kTabBarAddScale*controllerRightPercentage + 1);
        
        //渐变色
        [button1 setTitleColor:[UIColor colorWithRed:controllerLeftPercentage green:0 blue:0 alpha:1] forState:UIControlStateNormal];
        
        [button2 setTitleColor:[UIColor colorWithRed:controllerRightPercentage green:0 blue:0 alpha:1] forState:UIControlStateNormal];
        
    }else{
        NSUInteger idx = [self.subControllers indexOfObject:[arr lastObject]];
        [self buttonStateChange:[_tabBarButtons objectAtIndex:idx]];
    }
}

@end
